package com.java.code.insu;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.code.utils.date.DateUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.Charset;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author weichuanyuan
 * @e-mail wei.cy@bsoft.com.cn
 * @date 2021/12/3 21:27
 * @package com.java.code.insu
 * @description
 */
public class FileLoadInsu {
    public final static String _api_name_9101 = "hsa-fsi-9101";
    public final static String _api_name_9102 = "hsa-fsi-9102";
    public final static String _api_name_1309 = "hsa-fsi-1309";
    public final static String url = "http://10.77.224.18:9001/";
    public final static String _api_version = "1.0.0";
    //测试库
    public final static String _api_access_key = "f36c65fdce974ff78a34f42dcd8009da";
    public final static String secretKey = "drpcHvKLw19Rsb2Lv6gALGn6bmE=";

    /**
     * 文件上传接口
     *
     * @throws Exception
     */
    @Test
    public void test9101() throws Exception {
        //组织数据
        FsUploadIn data = new FsUploadIn();
        data.setFilename("test.zip");
        data.setFixmedinsCode("H36010200002");

        InputStream in = new FileInputStream("D:\\java_project\\code\\src\\main\\java\\com\\java\\code\\insu\\test.zip");
        byte[] bytes = toByteArray(in);
        in.close();
        data.setIn(bytes);

        Input input = new Input();
        input.setFsUploadIn(data);

        RootName root = new RootName();
        root.setInfno("9101");
        root.setMsgid("H36090202845202112032112260001");
        root.setMdtrtareaAdmvs("360999");
        root.setInsuplcAdmdvs("360999");
        root.setRecerSysCode("a01");
        root.setDevNo("");
        root.setDevSafeInfo("");
        root.setCainfo("");
        root.setSigntype("SM3");
        root.setInfver("1.0.0");
        root.setOpterType("1");
        root.setOpter("001");
        root.setOpterName("朱敏");
        root.setInfTime("2021-12-03 21:12:26");
        root.setFixmedinsCode("H36010200002");
        root.setFixmedinsName("江西省职业病医院");
        root.setSignNo("");
        root.setInput(input);

        ObjectMapper mapper = new ObjectMapper();
        String body = mapper.writeValueAsString(root);
        System.out.println(body);

        HttpEntity httpEntity = revoke(_api_name_9101, body);
        if (null == httpEntity) {
            System.out.println("调用失败！");
        } else {
            System.out.println(EntityUtils.toString(httpEntity, "UTF-8"));
        }
    }

    /**
     * 文件下载接口
     *
     * @throws Exception
     */
    @Test
    public void test9102() throws Exception {
        FsDownloadIn fsDownloadIn = new FsDownloadIn();
        fsDownloadIn.setFile_qury_no("fsi/plc/ba77707b72bf47fe92a2086f323a9e");
        fsDownloadIn.setFilename("202110257260844566831537646.txt.zip");
        fsDownloadIn.setFixmedins_code("H36010200002");

        Input input = new Input();
        input.setFsDownloadIn(fsDownloadIn);

        RootName root = new RootName();
        root.setInfno("9102");
        root.setMsgid("H36090202845202112032112260001");
        root.setMdtrtareaAdmvs("360999");
        root.setInsuplcAdmdvs("360999");
        root.setRecerSysCode("a01");
        root.setDevNo("");
        root.setDevSafeInfo("");
        root.setCainfo("");
        root.setSigntype("SM3");
        root.setInfver("1.0.0");
        root.setOpterType("1");
        root.setOpter("001");
        root.setOpterName("朱敏");
        root.setInfTime("2021-12-03 21:12:26");
        root.setFixmedinsCode("H36010200002");
        root.setFixmedinsName("江西省职业病医院");
        root.setSignNo("");
        root.setInput(input);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String body = mapper.writeValueAsString(root);
        System.out.println(body);

        HttpEntity httpEntity = revoke(_api_name_9102, body);
        if (null == httpEntity) {
            System.out.println("调用失败！");
        } else {
            OutputStream out = new FileOutputStream("D:\\java_project\\code\\src\\main\\java\\com\\java\\code\\insu\\202110257260844566831537646.txt.zip");
            httpEntity.writeTo(out);
        }
    }

    /**
     * 1309 门诊慢特病种目录下载
     *
     * @throws Exception
     */
    @Test
    public void test1309() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("ver", "M001_20210817000002_A");
        //map.put("list_type","301");

        Input input = new Input();
        input.setData(map);

        RootName root = new RootName();
        root.setInfno("1309");
        root.setMsgid("H36090202845202112032112260001");
        root.setMdtrtareaAdmvs("360999");
        root.setInsuplcAdmdvs("360999");
        root.setRecerSysCode("a01");
        root.setDevNo("");
        root.setDevSafeInfo("");
        root.setCainfo("");
        root.setSigntype("SM3");
        root.setInfver("1.0.0");
        root.setOpterType("1");
        root.setOpter("001");
        root.setOpterName("朱敏");
        root.setInfTime("2021-12-03 21:12:26");
        root.setFixmedinsCode("H36010200002");
        root.setFixmedinsName("江西省职业病医院");
        root.setSignNo("");
        root.setInput(input);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String body = mapper.writeValueAsString(root);
        System.out.println(body);

        HttpEntity httpEntity = revoke(_api_name_1309, body);
        if (null == httpEntity) {
            System.out.println("调用失败！");
        } else {
            System.out.println(EntityUtils.toString(httpEntity, "UTF-8"));
        }
    }

    /**
     * 调用
     *
     * @param api_name
     * @param body
     * @throws Exception
     */
    private HttpEntity revoke(String api_name, String body) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url + api_name);

        httppost.setHeader("Content-Type", "application/json");
        httppost.setHeader("user-agent", "Apache-HttpClient/4.5.13 (Java/1.8.0_301)");

        httppost.setHeader("_api_access_key", _api_access_key);
        httppost.setHeader("_api_version", _api_version);
        httppost.setHeader("_api_name", api_name);
        int _api_timestamp = DateUtils.secondTimestamp(new Date());
        httppost.setHeader("_api_timestamp", String.valueOf(_api_timestamp));


        String signStr = "_api_access_key=" + _api_access_key + "&_api_name=" + api_name + "&_api_timestamp=" + _api_timestamp + "&_api_version=" + _api_version;
        Mac mac = Mac.getInstance("HmacSHA1");
        Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(sKey);
        byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
        String _api_signature = new BASE64Encoder().encode(hash);

        httppost.setHeader("_api_signature", _api_signature);

        //设置body
        httppost.setEntity(new StringEntity(body, Charset.forName("UTF-8")));

        //使用httpclient进行连接
        CloseableHttpResponse response = client.execute(httppost);

        //查询成功
        if (response.getStatusLine().getStatusCode() == 200) {
            return response.getEntity();
        } else {
            System.out.println("返回失败！失败编码：" + String.valueOf(response.getStatusLine().getStatusCode()));
            return null;
        }
    }

    private byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /*==============RootName.java file============*/
    @lombok.Data
    @NoArgsConstructor
    public class RootName implements Serializable {
        private String infno;
        private String msgid;
        @JsonProperty("mdtrtarea_admvs")
        private String mdtrtareaAdmvs;
        @JsonProperty("insuplc_admdvs")
        private String insuplcAdmdvs;
        @JsonProperty("recer_sys_code")
        private String recerSysCode;
        @JsonProperty("dev_no")
        private String devNo;
        @JsonProperty("dev_safe_info")
        private String devSafeInfo;
        private String cainfo;
        private String signtype;
        private String infver;
        @JsonProperty("opter_type")
        private String opterType;
        private String opter;
        @JsonProperty("opter_name")
        private String opterName;
        @JsonProperty("inf_time")
        private String infTime;
        @JsonProperty("fixmedins_code")
        private String fixmedinsCode;
        @JsonProperty("fixmedins_name")
        private String fixmedinsName;
        @JsonProperty("sign_no")
        private String signNo;
        private Input input;

    }

    @lombok.Data
    @NoArgsConstructor
    public class FsUploadIn implements Serializable {
        @JsonProperty("in")
        private byte[] in;
        private String filename;
        @JsonProperty("fixmedins_code")
        private String fixmedinsCode;
    }

    @lombok.Data
    @NoArgsConstructor
    public class FsDownloadIn implements Serializable {
        @JsonProperty("file_qury_no")
        private String file_qury_no;
        /**
         * 下载【1301-1319】生成的文件，固定传入“plc”
         */
        private String filename;
        @JsonProperty("fixmedins_code")
        private String fixmedins_code;
    }

    @lombok.Data
    @NoArgsConstructor
    public class Input implements Serializable {
        private FsUploadIn fsUploadIn;

        private FsDownloadIn fsDownloadIn;

        private Object data;
    }
}
